package cool.taomu.software.fig.scheduler;

import java.util.List;
import java.util.Vector;
import java.util.concurrent.LinkedBlockingQueue;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cool.taomu.software.fig.mqtt.utils.CommonUtils;
import cool.taomu.software.fig.scheduler.annotation.Subscriber;
import cool.taomu.software.fig.scheduler.entity.SenderEntity;

public class Scheduler {
	private static final Logger LOG = LoggerFactory.getLogger(Scheduler.class);

	private static final LinkedBlockingQueue<SenderEntity> QUEUE = new LinkedBlockingQueue<SenderEntity>();

	private static final List<ISubscriber> SUBSCRIBERS = new Vector<>();

	static {
		CommonUtils.exec(new Runnable() {
			@Override
			public void run() {
				while (true) {
					SenderEntity se;
					try {
						se = QUEUE.take();
						synchronized (se) {
							for (ISubscriber sub : SUBSCRIBERS) {
								Subscriber a = sub.getClass().getAnnotation(Subscriber.class);
								if (a != null && a.value().equals(se.getTopic())) {
									sub.message(se.getMessage());
								}
							}
						}
					} catch (InterruptedException e) {
						e.printStackTrace();
					}

				}
			}
		});
	}
	
	public void register(ISubscriber sub) {
		SUBSCRIBERS.add(sub);
	}

	public void publish(SenderEntity message) {
		QUEUE.offer(message);
	}
}
